package com.application;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.application.adapter.MyRefreshAdapter;
import com.application.bean.NewsBean;
import com.application.databinding.ActivityRecyclerViewBinding;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

//@Route(path = ARouterConstants.ACTIVITY_URL_RECYCLER_VIEW)
public class RecyclerViewActivity extends AppCompatActivity {

    // ##################################################################
    // 旧代码：已废弃，用注释包裹，不参与编译（保留仅作参考）新代码在FindFragment
    // ##################################################################

    private ActivityRecyclerViewBinding binding;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private MyRefreshAdapter myRefreshAdapter;
    private int currentPage = 1;
    private final int PAGE_SIZE = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view);
        binding.setActivity(this);

        initView();
        initData();
        initAdapter();
        initRefreshEvent();

    }

    private void initView() {
        recyclerView = binding.recyclerView;
        refreshLayout = binding.recyclerRefresh;
        recyclerView.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);
    }

    /**
     * 初始化下拉刷新和上拉加载监听
     */
    private void initRefreshEvent() {
//        下拉刷新
        refreshLayout.setOnRefreshListener(refreshLayout -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
            currentPage = 1;
            myRefreshAdapter.setList(initData());
            refreshLayout.finishRefresh();
            Toast.makeText(RecyclerViewActivity.this, "刷新成功!", Toast.LENGTH_SHORT).show();
        }, 1500));

//        上拉加载
        refreshLayout.setOnLoadMoreListener(refreshLayout -> new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (currentPage >= 2) {
                refreshLayout.finishLoadMoreWithNoMoreData();
                Toast.makeText(RecyclerViewActivity.this, "已加载全部内容", Toast.LENGTH_SHORT).show();
                return;
            }
            currentPage++;
            List<NewsBean> newPage = loadMoreData();
            myRefreshAdapter.addData(newPage);
            refreshLayout.finishLoadMore();
            Toast.makeText(RecyclerViewActivity.this, "已加载第" + currentPage + "页", Toast.LENGTH_SHORT).show();
        }, 1500));
    }

    private void initAdapter() {
        myRefreshAdapter = new MyRefreshAdapter(initData());
        recyclerView.setAdapter(myRefreshAdapter);
        RecyclerView.LayoutManager defaultManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(defaultManager);

        myRefreshAdapter.setOnItemClickListener((adapter, view, position) -> {
            NewsBean clickedNews = (NewsBean) adapter.getData().get(position);
            Toast.makeText(this, "点击了:" + clickedNews.getTitle(), Toast.LENGTH_SHORT).show();
        });
    }


    /*
     *菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_recycler_view, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /*
     *点击切换布局
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.menu_linear) {
            RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(linearLayoutManager);
            return true;
        } else if (item.getItemId() == R.id.menu_grid) {
            RecyclerView.LayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
            recyclerView.setLayoutManager(gridLayoutManager);
            return true;
        } else if (item.getItemId() == R.id.menu_stagger) {
            RecyclerView.LayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
            recyclerView.setLayoutManager(staggeredGridLayoutManager);
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * 初始化第一页数据
     */
    private List<NewsBean> initData() {
        List<NewsBean> list = new ArrayList<>();
        for (int i = 0; i < PAGE_SIZE; i++) {
            NewsBean newsBean = new NewsBean();
            int dataIndex = (currentPage - 1) * PAGE_SIZE + (i + 1);
            switch (i) {
                case 0:
                    newsBean.setTitle("晨光漫杯（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("清晨阳光溜进窗，手捏温热马克杯，奶泡浮着浅黄小花。风裹着鸟鸣掠过，这刻不用赶时间，单是捧着暖饮，就觉日子软乎乎的。");
                    newsBean.setImageResourceId(R.drawable.chgmb);
                    break;
                case 1:
                    newsBean.setTitle("书角藏春（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("指尖拂过书页，夹在书里的干花轻轻晃。阳光落在字里行间，连墨香都裹着暖意，读不读得进内容没关系，这安静就很珍贵");
                    newsBean.setImageResourceId(R.drawable.sjcch);
                    break;
                case 2:
                    newsBean.setTitle("猫蜷膝头（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("猫咪踩着软脚垫跳上膝头，毛团般蜷成小球。呼吸轻轻拂过手背，窗外风摇树叶，这一刻，连时间都跟着慢下来，暖得让人想笑。");
                    newsBean.setImageResourceId(R.drawable.mqxt);
                    break;
                case 3:
                    newsBean.setTitle("雨打窗沿（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("雨点敲着玻璃窗，画出细碎水痕。窝在沙发裹着毯，听雨声混着轻音乐，手里捧着热汤，这样的雨天，比晴天更让人安心。");
                    newsBean.setImageResourceId(R.drawable.ydchy);
                    break;
                case 4:
                    newsBean.setTitle("晚灯拾趣（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("傍晚路灯亮起来，暖黄光晕圈着行人。买支甜筒慢慢走，晚风卷着草木香，连影子都跟着晃，平凡的夜晚也有小乐趣。");
                    newsBean.setImageResourceId(R.drawable.wdshq);
                    break;
            }
            list.add(newsBean);
        }
        return list;
    }

    /**
     * 加载更多数据
     */
    private List<NewsBean> loadMoreData() {
        List<NewsBean> newPage = new ArrayList<>();
        for (int i = 0; i < PAGE_SIZE; i++) {
            NewsBean newsBean = new NewsBean();
            int dataIndex = (currentPage - 1) * PAGE_SIZE + (i + 1);
            switch (i) {
                case 0:
                    newsBean.setTitle("茶烟绕指（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("紫砂壶倒出热茶，白雾绕着指尖转。茶叶在杯底舒展，抿一口满是甘醇，不慌不忙的时光里，连空气都变得温柔。");
                    newsBean.setImageResourceId(R.drawable.cxrz);
                    break;
                case 1:
                    newsBean.setTitle("笔落纸香（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("钢笔尖划过信纸，墨痕晕开淡淡的纸香。不用急着写什么，单是听笔尖的沙沙声，就觉心慢慢静下来，时光也变得柔软。");
                    newsBean.setImageResourceId(R.drawable.gb);
                    break;
                case 2:
                    newsBean.setTitle("弦音漫屋（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("指尖拨响吉他弦，浅吟的旋律绕着房间转。窗外蝉鸣轻轻和，不用在意音准，这一刻的松弛，比完美更让人舒心。");
                    newsBean.setImageResourceId(R.drawable.xymw);
                    break;
                case 3:
                    newsBean.setTitle("花映窗台（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("窗台上的小月季开了，粉瓣沾着晨露。阳光斜照过来，花瓣泛着微光，连风拂过都带着浅香，平凡的窗台，成了小而美的风景。");
                    newsBean.setImageResourceId(R.drawable.hycht);
                    break;
                case 4:
                    newsBean.setTitle("面包暖香（第" + currentPage + "页·" + dataIndex + "条）");
                    newsBean.setContent("烤箱 “叮” 声响起，刚出炉的吐司冒着热气。黄油轻轻抹开，裹着麦香飘满厨房，咬一口外脆里软，这口温热，是清晨最踏实的甜。");
                    newsBean.setImageResourceId(R.drawable.mbnx);
                    break;
            }
            newPage.add(newsBean);
        }
        return newPage;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
}